package com.dimension.utils;

import cn.hutool.core.util.StrUtil;
import com.dimension.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtil {

//    public static final long EXPIRE = 1000 * 60 * 30; // 半小时
    public static final long EXPIRE = 1000 * 60 * 60 * 24 * 30; // 30天
    public static final String SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    public static String createToken(User user){
        String JwtToken = Jwts.builder()
                //JWT头信息
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS2256")
                .setSubject("lx-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))

                // 主体
                .claim("user", user)

                // 签名
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
        return JwtToken;
    }

    public static boolean checkToken(String jwtToken){
        if (StrUtil.isEmpty(jwtToken)){
            return false;
        }
        try{
            //验证token
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(jwtToken);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static User getUser(String token){
        if (StrUtil.isEmpty(token)){
            return null;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
        Claims body = claimsJws.getBody();

        // 获取user
        User user = (User) body.get("user");
        return user;
    }
}
